<?php

/**
 * 框架无关设计示例
 * 
 * 展示如何在不同PHP框架中使用lkExportExcel
 * 数据获取由用户/框架负责，Excel处理由库负责
 */

require_once __DIR__ . '/../vendor/autoload.php';

use LkExcel\LkExportExcel\Api\Writer;

echo "🎯 框架无关设计示例\n";
echo "===================\n\n";

// ===========================================
// 1. Laravel框架示例
// ===========================================
echo "📱 Laravel框架集成示例:\n";
echo "```php\n";
echo "// Laravel用户的代码\n";
echo "use App\\Models\\User;\n";
echo "use LkExcel\\LkExportExcel\\Api\\Writer;\n";
echo "\n";
echo "// 用户负责数据获取（可以使用任何Laravel特性）\n";
echo "function getUserData() {\n";
echo "    return User::with('profile')\n";
echo "               ->where('active', true)\n";
echo "               ->chunk(1000, function(\$users) {\n";
echo "                   foreach (\$users as \$user) {\n";
echo "                       yield [\n";
echo "                           'id' => \$user->id,\n";
echo "                           'name' => \$user->name,\n";
echo "                           'email' => \$user->email,\n";
echo "                           'profile' => \$user->profile->bio ?? '',\n";
echo "                       ];\n";
echo "                   }\n";
echo "               });\n";
echo "}\n";
echo "\n";
echo "// 库只负责Excel处理\n";
echo "\$writer = new Writer();\n";
echo "\$writer->startWrite('users.xlsx')\n";
echo "       ->fromDataSource(getUserData())\n";
echo "       ->finishWrite();\n";
echo "```\n\n";

// ===========================================
// 2. ThinkPHP框架示例
// ===========================================
echo "🧠 ThinkPHP框架集成示例:\n";
echo "```php\n";
echo "// ThinkPHP用户的代码\n";
echo "use think\\facade\\Db;\n";
echo "use LkExcel\\LkExportExcel\\Api\\Writer;\n";
echo "\n";
echo "// 用户负责数据获取（使用ThinkPHP的数据库操作）\n";
echo "function getOrderData() {\n";
echo "    \$query = Db::table('orders')\n";
echo "                ->alias('o')\n";
echo "                ->join('users u', 'o.user_id = u.id')\n";
echo "                ->field('o.id, o.total, u.name, o.created_time')\n";
echo "                ->where('o.status', 'completed');\n";
echo "    \n";
echo "    // 分批处理，避免内存问题\n";
echo "    \$offset = 0;\n";
echo "    \$limit = 1000;\n";
echo "    \n";
echo "    while (true) {\n";
echo "        \$orders = \$query->limit(\$offset, \$limit)->select();\n";
echo "        if (empty(\$orders)) break;\n";
echo "        \n";
echo "        foreach (\$orders as \$order) {\n";
echo "            yield \$order;\n";
echo "        }\n";
echo "        \n";
echo "        \$offset += \$limit;\n";
echo "    }\n";
echo "}\n";
echo "\n";
echo "// 库只负责Excel处理\n";
echo "\$writer = new Writer();\n";
echo "\$writer->startWrite('orders.csv')\n";
echo "       ->fromDataSource(getOrderData())\n";
echo "       ->finishWrite();\n";
echo "```\n\n";

// ===========================================
// 3. 原生PHP + PDO示例
// ===========================================
echo "🔧 原生PHP + PDO示例:\n";
echo "```php\n";
echo "// 原生PHP用户的代码\n";
echo "use LkExcel\\LkExportExcel\\Api\\Writer;\n";
echo "\n";
echo "// 用户负责数据库连接和查询优化\n";
echo "function getDatabaseData(\$pdo) {\n";
echo "    // 用户可以做任何数据库优化\n";
echo "    \$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);\n";
echo "    \n";
echo "    \$stmt = \$pdo->prepare('SELECT * FROM products WHERE status = ?');\n";
echo "    \$stmt->execute(['active']);\n";
echo "    \n";
echo "    while (\$row = \$stmt->fetch(PDO::FETCH_ASSOC)) {\n";
echo "        yield \$row;\n";
echo "    }\n";
echo "}\n";
echo "\n";
echo "// 库只负责Excel处理\n";
echo "\$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');\n";
echo "\$writer = new Writer();\n";
echo "\$writer->startWrite('products.xlsx')\n";
echo "       ->fromDataSource(getDatabaseData(\$pdo))\n";
echo "       ->finishWrite();\n";
echo "```\n\n";

// ===========================================
// 4. API数据源示例
// ===========================================
echo "🌐 API数据源示例:\n";
echo "```php\n";
echo "// 从API获取数据\n";
echo "function getApiData() {\n";
echo "    \$page = 1;\n";
echo "    \$perPage = 100;\n";
echo "    \n";
echo "    while (true) {\n";
echo "        \$response = file_get_contents(\"https://api.example.com/users?page={\$page}&per_page={\$perPage}\");\n";
echo "        \$data = json_decode(\$response, true);\n";
echo "        \n";
echo "        if (empty(\$data['data'])) break;\n";
echo "        \n";
echo "        foreach (\$data['data'] as \$user) {\n";
echo "            yield [\n";
echo "                'id' => \$user['id'],\n";
echo "                'name' => \$user['name'],\n";
echo "                'email' => \$user['email'],\n";
echo "            ];\n";
echo "        }\n";
echo "        \n";
echo "        \$page++;\n";
echo "    }\n";
echo "}\n";
echo "\n";
echo "\$writer = new Writer();\n";
echo "\$writer->startWrite('api_users.csv')\n";
echo "       ->fromDataSource(getApiData())\n";
echo "       ->finishWrite();\n";
echo "```\n\n";

// ===========================================
// 5. 实际运行示例（模拟数据）
// ===========================================
echo "🚀 实际运行示例（模拟数据）:\n";

// 模拟不同数据源
function mockDatabaseData() {
    echo "      📊 模拟数据库数据源...\n";
    for ($i = 1; $i <= 5000; $i++) {
        yield [
            'id' => $i,
            'name' => "用户{$i}",
            'email' => "user{$i}@example.com",
            'created_at' => date('Y-m-d H:i:s', time() - rand(0, 86400 * 365))
        ];
    }
}

function mockApiData() {
    echo "      🌐 模拟API数据源...\n";
    for ($i = 1; $i <= 3000; $i++) {
        yield [
            'product_id' => $i,
            'title' => "产品{$i}",
            'price' => rand(10, 1000) / 10,
            'category' => ['电子', '服装', '图书', '家居'][rand(0, 3)]
        ];
    }
}

// 测试数据库数据导出
echo "\n1. 测试数据库数据导出:\n";
$writer = new Writer();
$writer->startWrite(__DIR__ . '/../output/framework_demo_database.csv')
       ->fromDataSource(mockDatabaseData())
       ->finishWrite();

// 测试API数据导出
echo "\n2. 测试API数据导出:\n";
$writer = new Writer();
$writer->startWrite(__DIR__ . '/../output/framework_demo_api.xlsx')
       ->fromDataSource(mockApiData())
       ->finishWrite();

// 测试数据映射
echo "\n3. 测试数据映射功能:\n";
$writer = new Writer();
$writer->startWrite(__DIR__ . '/../output/framework_demo_mapped.csv')
       ->fromDataSource(mockDatabaseData(), function($item) {
           // 用户可以自定义数据映射
           return [
               '用户ID' => $item['id'],
               '用户名称' => strtoupper($item['name']),
               '邮箱地址' => $item['email'],
               '注册日期' => date('Y年m月d日', strtotime($item['created_at']))
           ];
       })
       ->finishWrite();

echo "\n✅ 所有示例运行完成！\n";
echo "\n🎯 核心设计优势:\n";
echo "   ✅ 框架无关：支持任何PHP框架\n";
echo "   ✅ 数据源灵活：数据库、API、文件、缓存等\n";
echo "   ✅ 职责分离：用户负责数据，库负责Excel\n";
echo "   ✅ 性能优化：流式处理，内存恒定\n";
echo "   ✅ 易于测试：不依赖外部资源\n\n"; 